<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Initial System</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>

<div class="container">
  <div class="row">
    <div class="col s8 push-s2 m6 push-m3" id="panel">
    </div>
  </div>
</div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>

    function outputMessage(message){
      $('#error').text(message);
    }

    function initial() {
      var nameExp = new RegExp('[^\\w-.]');
      var username = $('#username').val();
      if (!username){
        outputMessage('please input user name');
        return;
      }
      if (nameExp.test(username)){
        outputMessage("only letter/digit/'-'/'_'/'.' allowed in username");
        return;
      }
      var password = $('#password').val();
      if (!password){
        outputMessage('please input password');
        return;
      }
      if (password != $('#password2').val()){
        outputMessage('two passwords are unmatched.');
        return;
      }
      var request = new Object();
      request.password = password;
      $.post(
        '/users/'+ username,
        JSON.stringify(request),
        function(result){
          if (0 != result['error_code']) {
            outputMessage(result['message']);
            return;
          }
          //create super role
          createSuperRole(username);
        },
        "json"
      );
    }

    function createSuperRole(username){
      var rolename = 'super';
      var menu = new Array();
      N.GetAllMenus().forEach((item)=>{
        menu.push(item[0]);
      });
      var request = new Object();
      request.menu = menu;
      $.post(
        '/roles/'+ rolename,
        JSON.stringify(request),
        function(result){
          if (0 != result['error_code']) {
            outputMessage(result['message']);
            return;
          }
          createAdminGroup(rolename, username);
        },
        "json"
      );
    }

    function createAdminGroup(roleName, userName){
      var groupName = "admin";
      var request = new Object();
      request.display = "Adminitrators of Nano";
      request.role = [roleName];
      $.post(
        '/user_groups/'+ groupName,
        JSON.stringify(request),
        function(result){
          if (0 != result['error_code']) {
            outputMessage(result['message']);
            return;
          }
          addUserToGroup(userName, groupName);
        },
        "json"
      );
    }

    function addUserToGroup(userName, groupName){
      $.post(
        '/user_groups/'+ groupName + '/members/' + userName,
        "",
        function(result){
          if (0 != result['error_code']) {
            outputMessage(result['message']);
            return;
          }
          M.toast({html: 'create new admin ' + userName + ' success, redirect to login page'});
          var loginPage = "login.html";
          window.location.replace(loginPage);
        },
        "json"
      );
    }

    $(function(){
      N.CreateMenuAndFooter();
      M.AutoInit();
      var texts = N.GetTexts();
      var panel = $('#panel').empty();
      var titleText, descriptionText;
      if (N.IsChinese()){
        titleText = '欢迎使用Nano云平台';
        descriptionText = "请设定管理员账号及密码，开始初始化系统";
      }else{
        titleText = 'Welcome to Nano';
        descriptionText = "Please set up a new admin account";
      }
      panel.append(
        $('<div>').addClass('row').append(
          $('<div>').addClass('col m6').append(
            $('<div>').addClass('row').append(
              $('<span>').addClass('flow-text').text(titleText)
            )
          ).append(
            $('<div>').addClass('row').append(
              $('<span>').text(descriptionText)
            )
          )
        )
      ).append(
        $('<div>').addClass('row').append(
          $('<div>').addClass('input-field col m6').append(
            $('<input>').attr('type', 'text').attr('id', 'username')
          ).append(
            $('<label>').attr('for', 'username').text(texts.get(N.TagUser))
          )
        )
      ).append(
        $('<div>').addClass('row').append(
          $('<div>').addClass('input-field col m6').append(
            $('<input>').attr('type', 'password').attr('id', 'password')
          ).append(
            $('<label>').attr('for', 'password').text(texts.get(N.TagPassword))
          )
        )
      ).append(
        $('<div>').addClass('row').append(
          $('<div>').addClass('input-field col m6').append(
            $('<input>').attr('type', 'password').attr('id', 'password2')
          ).append(
            $('<label>').attr('for', 'password2').text(texts.get(N.TagConfirm) + ' ' + texts.get(N.TagPassword))
          )
        )
      ).append(
        $('<div>').addClass('row').append(
          $('<div>').addClass('col m6').append(
              $('<span>').attr('id', 'error').addClass('red-text')
          )
        )
      ).append(
        $('<div>').addClass('row').append(
          $('<div>').addClass('col m3').append(
            $('<button>').addClass('waves-effect waves-light blue-grey lighten-2 btn').attr('onclick', 'initial()').append(
              $('<i>').addClass('material-icons right').text('add')
            ).append(
              texts.get(N.TagCreate)
            )
          )
        )
      );
    });

</script>
</body>
</html>
